/**
 * 简单的SPA路由管理器
 * 用于在Web环境下模拟微信小程序的页面跳转
 */

import { reactive } from 'vue'

// 导入页面组件
import LoginPage from './pages/login/login-web.vue'
import RegisterPage from './pages/register/register.vue'
import ForgotPasswordPage from './pages/forgot-password/forgot-password.vue'
import IndexPage from './pages/index/index.vue'

// 路由配置
const routes = {
  '/pages/login/login': LoginPage,
  '/pages/register/register': RegisterPage,
  '/pages/forgot-password/forgot-password': ForgotPasswordPage,
  '/pages/index/index': IndexPage
}

// 响应式路由状态
export const router = reactive({
  currentRoute: '/pages/login/login',
  history: ['/pages/login/login'],

  // 获取当前页面组件
  getCurrentComponent () {
    return routes[this.currentRoute] || LoginPage
  },

  // 导航到指定页面
  navigateTo (url) {
    if (routes[url]) {
      this.history.push(url)
      this.currentRoute = url
      console.log('导航到:', url)
    } else {
      console.warn('页面不存在:', url)
    }
  },

  // 重定向到指定页面（清空历史记录）
  redirectTo (url) {
    if (routes[url]) {
      this.history = [url]
      this.currentRoute = url
      console.log('重定向到:', url)
    } else {
      console.warn('页面不存在:', url)
    }
  },

  // 返回上一页
  navigateBack () {
    if (this.history.length > 1) {
      this.history.pop()
      this.currentRoute = this.history[this.history.length - 1]
      console.log('返回到:', this.currentRoute)
    } else {
      console.log('已经是第一页，无法返回')
    }
  }
})

// 扩展全局uni对象，添加路由功能
window.uni = {
  ...window.uni,
  navigateTo: ({ url }) => router.navigateTo(url),
  redirectTo: ({ url }) => router.redirectTo(url),
  navigateBack: () => router.navigateBack()
}

export default router